package com.systop.tea.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.systop.tea.common.R;
import com.systop.tea.entity.User;
import com.systop.tea.service.UserService;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;

@RestController
@RequiredArgsConstructor
@RequestMapping("/user")
public class UserController {

    private final UserService userService;

    @PostMapping("/login")
    public R<User> login(@RequestBody User user) {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getPhone, user.getPhone());
        queryWrapper.eq(User::getPassword, user.getPassword());
        User user1 = userService.getOne(queryWrapper);
        if (user1 != null)
            return R.success(user1);
        else
            return R.error("账号或密码错误");
    }


    // 分页、条件查询
    @GetMapping("/query")
    public R<Page> query(User user, Integer pageNum, Integer pageSize) {
        Page page = new Page(pageNum, pageSize);
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(StringUtils.isNotBlank(user.getUsername()), User::getUsername, user.getUsername());
        userService.page(page, queryWrapper);

        return R.success(page);
    }

    // 根据id查询
    @GetMapping("/{id}")
    public R<User> queryById(@PathVariable Integer id) {
        User user = userService.getById(id);
        return R.success(user);
    }

    // 添加用户
    @PostMapping
    public R<String> add(@RequestBody User user) {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getPhone, user.getPhone());
        User one = userService.getOne(queryWrapper);
        if (one != null) {
            return R.error("手机号已被注册");
        }
        user.setAddTime(LocalDateTime.now());
        boolean rows = userService.save(user);
        if (rows)
            return R.success("用户添加成功");
        else
            return R.error("用户添加失败");
    }

    // 修改用户
    @PutMapping
    public R<String> modify(@RequestBody User user) {
        boolean rows = userService.updateById(user);
        if (rows)
            return R.success("用户修改成功");
        else
            return R.error("用户修改失败");
    }

    // 删除用户
    @DeleteMapping("/{id}")
    public R<String> delete(@PathVariable Integer id) {
        boolean rows = userService.removeById(id);
        if (rows) {
            return R.success("用户删除成功");
        } else {
            return R.error("用户删除失败");
        }
    }

}
